package com.avic.rong.userOrder.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.activity.OrderDetailsActivity;
import com.avic.rong.userOrder.activity.OrderDetailsPXActivity;
import com.avic.rong.userOrder.api.ConfirmReceiptApi;
import com.avic.rong.userOrder.bean.GetOrderTracesByJsonAllBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.GlideUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.GlideApp;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by XinEr on 2019/7/19.
 * Describe:
 */
public class OrderPathVpAdapter extends PagerAdapter {
    private Context mContext;

    private ArrayList<GetOrderTracesByJsonAllBean.OrderTracesListBean.TracesListBean> wuliuListData;

    private RecyclerView path_recylist;
    private TextView tv_starte;
    private TextView tv_wuliu_company;
    private TextView tv_configm_btn;
    private TextView tv_shou_address;
    private TextView tv_look_order;
    private ImageView iv_order_pic;
    private NestedScrollView scroll_view;
    private LinearLayout ll_order_details;
    private TextView tv_no_path;
    private GetOrderTracesByJsonAllBean.OrderTracesListBean.TracesListBean tracesListBean;

    public static String ORDER_ID = "order_id";
    public static String ORDER_SN = "order_sn";
    private int COMMENT_FORCODE = 6;
    private PopupWindow popupWindow;

    private TextView tv_goods_type;
    private TextView tv_goods_tel;
    private LinearLayout ll_pic_tag;

    public OrderPathVpAdapter(Context context, ArrayList<GetOrderTracesByJsonAllBean.OrderTracesListBean.TracesListBean> wuliuListData) {
        this.mContext = context;
        this.wuliuListData = wuliuListData;
    }

    public PopupWindow getPopupWindow() {
        return popupWindow;
    }

    public void setPopupWindow(PopupWindow popupWindow) {
        this.popupWindow = popupWindow;
    }

    @Override
    public int getCount() {
        return wuliuListData.size();
    }

    /**
     * 判断是否使用缓存, 如果返回的是true, 使用缓存. 不去调用instantiateItem方法创建一个新的对象
     */
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    /**
     * 初始化一个条目
     *
     * @param container
     * @param position  当前需要加载条目的索引
     * @return
     */
    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.order_path_dialog_item, null);
        path_recylist = view.findViewById(R.id.path_recylist);
        tv_starte = view.findViewById(R.id.tv_starte);
        tv_wuliu_company = view.findViewById(R.id.tv_wuliu_company);
        tv_configm_btn = view.findViewById(R.id.tv_configm_btn);
        tv_look_order = view.findViewById(R.id.tv_look_order);
        iv_order_pic = view.findViewById(R.id.iv_goods_pic);
        tv_shou_address = view.findViewById(R.id.tv_shou_address);
        scroll_view = view.findViewById(R.id.scroll_view);
        ll_order_details = view.findViewById(R.id.ll_order_details);
        tv_no_path = view.findViewById(R.id.tv_no_path);
        tv_goods_type = view.findViewById(R.id.tv_goods_type);
        tv_goods_tel = view.findViewById(R.id.tv_goods_tel);
        ll_pic_tag = view.findViewById(R.id.ll_pic_tag);

        tracesListBean = wuliuListData.get(position);


        if (tracesListBean.getOrderType() == 4) {
            if (!TextUtils.isEmpty(tracesListBean.getProImg())) {
                if (tracesListBean.getProImg().contains("rongrong.")) {
                    GlideUtils.loaderImage(mContext, tracesListBean.getProImg(), iv_order_pic);
                } else {
                    GlideUtils.loaderImage(mContext, tracesListBean.getBiaoZhunImg() + tracesListBean.getProImg(), iv_order_pic);
                }
                iv_order_pic.setVisibility(View.VISIBLE);
                ll_pic_tag.setVisibility(View.GONE);
            } else {
                String keywords = tracesListBean.getKeywords();
                String catName = tracesListBean.getCatName();
                tv_goods_type.setText(catName);
                tv_goods_tel.setText(keywords);
                ll_pic_tag.setVisibility(View.VISIBLE);
                iv_order_pic.setVisibility(View.VISIBLE);
                GlideApp.with(mContext).load(R.mipmap.common_bg).centerCrop().into(iv_order_pic);
//                Glide.with(mContext).load(R.mipmap.common_bg).into(iv_order_pic);
            }
        } else {
            if (!TextUtils.isEmpty(tracesListBean.getProImg())) {
                GlideUtils.loaderImage(mContext, tracesListBean.getProImg(), iv_order_pic);
                iv_order_pic.setVisibility(View.VISIBLE);
                ll_pic_tag.setVisibility(View.GONE);
            } else {
                //默认图
//                GlideUtils.loaderImage(context, R.mipmap.common_bg, iv_goods_pic);
                String keywords = tracesListBean.getKeywords();
                String catName = tracesListBean.getCatName();
                tv_goods_type.setText(catName);
                tv_goods_tel.setText(keywords);
                GlideApp.with(mContext).load(R.mipmap.common_bg).centerCrop().into(iv_order_pic);
//                Glide.with(mContext).load(R.mipmap.common_bg).into(iv_order_pic);
                iv_order_pic.setVisibility(View.VISIBLE);
                ll_pic_tag.setVisibility(View.VISIBLE);
            }

        }


//        GlideUtils.loaderImage(mContext, tracesListBean.getProImg(), iv_order_pic);
        tv_shou_address.setText("【收货地址】"+tracesListBean.getUserAddress());
//        Glide.with(mContext).load(tracesListBean.getProImg()).into(iv_order_pic);
        //        物流状态0： 无轨迹，1：已揽收，2：在途中，3：签收，4：问题件
        if (tracesListBean.getState()!=null){
            if (tracesListBean.getState().equals("0")) {
                tv_starte.setText("无轨迹");
            } else if (tracesListBean.getState().equals("1")) {
                tv_starte.setText("已揽收");
            } else if (tracesListBean.getState().equals("2")) {
                tv_starte.setText("在途中");
            } else if (tracesListBean.getState().equals("3")) {
                tv_starte.setText("签收");
            } else if (tracesListBean.getState().equals("4")) {
                tv_starte.setText("问题件");
            }
        }else {
            tv_starte.setText("无轨迹");
        }

//        物流:SF:顺丰快递, ZTO: 中通快递 ,EMS:EMS邮政快递
        if (tracesListBean.getShipperCode().equals("SF")) {
            tv_wuliu_company.setText("快递公司:  顺丰快递");
        } else if (tracesListBean.getShipperCode().equals("ZTO")) {
            tv_wuliu_company.setText("快递公司:  中通快递");
        } else if (tracesListBean.getShipperCode().equals("EMS")) {
            tv_wuliu_company.setText("快递公司:  EMS邮政快递");
        }

        if (tracesListBean.getTraces() == null || tracesListBean.getTraces().size() <= 0) {
            scroll_view.setVisibility(View.GONE);
            tv_no_path.setVisibility(View.VISIBLE);
        } else {

            List<GetOrderTracesByJsonAllBean.OrderTracesListBean.TracesListBean.TracesBean> traces = tracesListBean.getTraces();
            path_recylist.setLayoutManager(new LinearLayoutManager(mContext));
            OrderPathListAdapter orderPathListAdapter = new OrderPathListAdapter(mContext, traces);
            path_recylist.setAdapter(orderPathListAdapter);
            scroll_view.setVisibility(View.VISIBLE);
            tv_no_path.setVisibility(View.GONE);
        }

        tv_configm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                configmOrder();
            }
        });
        ll_order_details.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetOrderTracesByJsonAllBean.OrderTracesListBean.TracesListBean tracesDetails = wuliuListData.get(position);
                if (tracesDetails.getOrderType() != 5 && !TextUtils.isEmpty(tracesDetails.getOrderType() + "")) {
                    Intent intent = new Intent(mContext, OrderDetailsActivity.class);
                    intent.putExtra(ORDER_ID, tracesDetails.getOrderId() + "");
                    intent.putExtra(OrderDetailsActivity.ORDER_JUMP, "mine_home");
                    ((MainActivity) mContext).startActivityForResult(intent, COMMENT_FORCODE);
                } else {
                    Intent intent = new Intent(mContext, OrderDetailsPXActivity.class);
                    intent.putExtra(ORDER_SN, tracesDetails.getOrderId() + "");
                    intent.putExtra(OrderDetailsPXActivity.ORDER_JUMP, "mine_home");
                    ((MainActivity) mContext).startActivityForResult(intent, COMMENT_FORCODE);

                }
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
//        TextView tvTitle = view.findViewById(R.id.tv_title);
//        if (!StringUtil.isEmpty(urlList.get(position%urlList.size()).getTitle())){
//            tvTitle.setText(urlList.get(position%urlList.size()).getTitle());
//        }

//        final SimpleImageView banner_image = view.findViewById(R.id.banner_image);
//        banner_image.setImageUrl(urlList.get(position % urlList.size()).getBigImgUrl());
//
//        banner_image.setOnClickListener(new OnClickLimitListener() {
//
//            @Override
//            public void onClickLimit(View v) {
//
//                Navigate.enterDetailActivity(mContext, urlList.get(position % urlList.size()));
//
//            }
//        });
        container.addView(view);
        return view;
    }

    private void configmOrder() {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", tracesListBean.getOrderId() + "");
        map.put("token", SharedPreferencesUtil.getInstance(mContext).getLogintoken());
        final ConfirmReceiptApi confirmReceiptApi = new ConfirmReceiptApi((MainActivity) mContext, simpleOnNextListener);
        confirmReceiptApi.setCache(false);
        confirmReceiptApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(confirmReceiptApi);
    }

    /**
     * 销毁一个条目
     * position 就是当前需要被销毁的条目的索引
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // 把ImageView从ViewPager中移除掉
        container.removeView((View) object);

    }

    //确认收货
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(mContext, subjects.getMsg());
                return;
            }
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.CLOSE_DIALOG_INFORM);
            EventBus.getDefault().post(informUpdate);

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };

}
